package cn.virens.web.components.open.session;

import java.io.Serializable;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 微信Session对象
 * 
 * @author virens
 */
public class WxSessionImpl implements WxSession, Serializable {
	private static final long serialVersionUID = 7160779239673823661L;

	private Map<String, Object> sessionAttrs = new ConcurrentHashMap<>();

	public WxSessionImpl() {

	}

	public WxSessionImpl(WxSession session) {
		for (String attrName : session.getAttributeNames()) {
			Object attrValue = session.getAttribute(attrName);
			if (attrValue != null && !"".equals(attrValue)) {
				this.sessionAttrs.put(attrName, attrValue);
			}
		}
	}

	@Override
	@SuppressWarnings("unchecked")
	public <T> T getAttribute(String name) {
		return (T) sessionAttrs.get(name);
	}

	@Override
	public Set<String> getAttributeNames() {
		return sessionAttrs.keySet();
	}

	@Override
	public <T> void setAttribute(String attributeName, T attributeValue) {
		if (attributeValue != null || "".equals(attributeValue)) {
			this.sessionAttrs.put(attributeName, attributeValue);
		} else {
			this.removeAttribute(attributeName);
		}
	}

	@Override
	public void removeAttribute(String name) {
		this.sessionAttrs.remove(name);
	}

	@Override
	public void invalidate() {
		this.sessionAttrs.clear();
	}

	@Override
	public boolean isExpired() {
		return sessionAttrs.isEmpty();
	}
}
